//
//  ZCameraShot.m
//  danpin
//
//  Created by chuangjia on 5/8/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "ZCameraShot.h"
#import "UIImage+Resize.h"
@import AssetsLibrary;
@implementation ZCameraShot

+ (void)takePhotoCaptureView:(UIView *)captureView stillImageOutput:(AVCaptureStillImageOutput *)stillImageOutput effectiveScale:(NSInteger)effectiveScale videoOrientation:(AVCaptureVideoOrientation)videoOrientation completion:(void (^)(UIImage *))completion
{
    AVCaptureConnection *videoConnection = nil;
    
    for (AVCaptureConnection *connection in [stillImageOutput connections]) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                videoConnection = connection;
                break;
            }
        }
        
        if (videoConnection) {
            break;
        }
    }
    
    [videoConnection setVideoOrientation:videoOrientation];
    [videoConnection setVideoScaleAndCropFactor:effectiveScale];
    
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
                                                  completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
                                                      if (imageDataSampleBuffer != NULL) {
                                                          NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                          UIImage *image = [UIImage imageWithData:imageData];
                                                        
                                                          CGFloat squareLength =  [[UIScreen mainScreen] applicationFrame].size.width;
                                                          CGFloat headHeight = 0;//_previewLayer的frame是(0, 44, 320, 320 + 44)
                                                          CGSize size = CGSizeMake(squareLength * 2, squareLength * 2);
                                                          
                                                          UIImage *scaledImage = [image resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:size interpolationQuality:kCGInterpolationHigh];
                                                    
                                                          CGRect cropFrame = CGRectMake((scaledImage.size.width - size.width) / 2, (scaledImage.size.height - size.height) / 2 + headHeight, size.width, size.height);
                                                          UIImage *croppedImage = [scaledImage croppedImage:cropFrame];
                                                          
                                                          
                                                          UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
                                                          if (orientation != UIDeviceOrientationPortrait) {
                                                              
                                                              CGFloat degree = 0;
                                                              if (orientation == UIDeviceOrientationPortraitUpsideDown) {
                                                                  degree = 180;// M_PI;
                                                              } else if (orientation == UIDeviceOrientationLandscapeLeft) {
                                                                  degree = -90;// -M_PI_2;
                                                              } else if (orientation == UIDeviceOrientationLandscapeRight) {
                                                                  degree = 90;// M_PI_2;
                                                              }
                                                              croppedImage = [croppedImage rotatedByDegrees:degree];
                                                          }
                                                          completion(croppedImage);
                                                      }
                                                  }];
  
    
}
+ (void)takePhotoCaptureViewForCard:(UIView *)captureView
                   stillImageOutput:(AVCaptureStillImageOutput *)stillImageOutput
                     effectiveScale:(NSInteger)effectiveScale
                   videoOrientation:(AVCaptureVideoOrientation)videoOrientation
                         completion:(void (^)(UIImage *photo))completion
{
    AVCaptureConnection *videoConnection = nil;
    
    for (AVCaptureConnection *connection in [stillImageOutput connections]) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                videoConnection = connection;
                break;
            }
        }
        
        if (videoConnection) {
            break;
        }
    }
    
    [videoConnection setVideoOrientation:videoOrientation];
    [videoConnection setVideoScaleAndCropFactor:effectiveScale];
    
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
                                                  completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
                                                      if (imageDataSampleBuffer != NULL) {
                                                          NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                                                          UIImage *image = [UIImage imageWithData:imageData];

                                                          UIImage *croppedImage = [self scaleImage:image toScale:0.5];
                                                          completion(croppedImage);
                                                      }
                                                  }];
}

+(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
@end
